<?php

namespace Cblood\Sword\Database;


class Connection
{
    /**
     * @var \PDO
     */
    protected $pdo;

    protected $lastCount;

    protected $lastSql;

    public function __construct($dsn, $username, $password)
    {
        $this->pdo = new \PDO($dsn, $username, $password);
    }

    /**
     * 查询数据库
     * @param string $sql
     * @return Result
     */
    public function select($sql)
    {
        $this->lastSql = $sql;
        return new Result($this->pdo->query($sql));
    }

    /**
     * 执行sql语句，通常是增删改
     * @param $sql
     * @return bool
     */
    public function execute($sql)
    {
        $this->lastSql = $sql;
        $this->lastCount = $this->pdo->exec($sql);
        return $this->lastCount ? true : false;
    }

    public function beginTransaction()
    {
        $this->pdo->beginTransaction();
    }

    public function commit()
    {
        $this->pdo->commit();
    }

    public function rollBack()
    {
        $this->pdo->rollBack();
    }

    /**
     * 获取上一句sql影响的行数
     * @return int
     */
    public function lastCount()
    {
        return $this->lastCount;
    }

    /**
     * 获取上一句 insert sql 的自增长id
     * @return int
     */
    public function lastInsertId()
    {
        return $this->pdo->lastInsertId();
    }

    /**
     * 上一次执行的sql语句
     * 通常可用作调试
     * @return mixed
     */
    public function lastSql()
    {
        return $this->lastSql;
    }
}